﻿using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;

namespace AppConfigCodeGenerator
{
    [Guid("3781BEE9-E969-43ac-BDBD-E7D54F2C5528")]
    public class AppConfigCodeGeneratorCustomTool : IVsSingleFileGenerator
    {
        #region IVsSingleFileGenerator Membres

        /// <summary>
        /// Defaults the extension.
        /// </summary>
        /// <param name="pbstrDefaultExtension">The PBSTR default extension.</param>
        /// <returns></returns>
        public int DefaultExtension(out string pbstrDefaultExtension)
        {
            pbstrDefaultExtension = ".cs";
            return 0;
        }

        /// <summary>
        /// Generates the specified WSZ input file path.
        /// </summary>
        /// <param name="wszInputFilePath">The WSZ input file path.</param>
        /// <param name="bstrInputFileContents">The BSTR input file contents.</param>
        /// <param name="wszDefaultNamespace">The WSZ default namespace.</param>
        /// <param name="rgbOutputFileContents">The RGB output file contents.</param>
        /// <param name="pcbOutput">The PCB output.</param>
        /// <param name="pGenerateProgress">The p generate progress.</param>
        /// <returns></returns>
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            if (bstrInputFileContents == null)
                throw new ArgumentNullException(bstrInputFileContents);

            String applicationName = wszDefaultNamespace;
            if (wszDefaultNamespace.IndexOf('.') > 0)
            {
                applicationName = wszDefaultNamespace.Substring(0, wszDefaultNamespace.IndexOf('.'));
            }

            byte[] generatedStuff = System.Text.Encoding.UTF8.GetBytes(CodeGenerator.Generate(wszDefaultNamespace, applicationName, CodeGenerator.AvailableLanguage.CSharp, wszInputFilePath));

            if (generatedStuff == null)
            {
                rgbOutputFileContents[0] = IntPtr.Zero;
                pcbOutput = 0;
            }
            else
            {
                // Stream copy
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(generatedStuff.Length);
                Marshal.Copy(generatedStuff, 0, rgbOutputFileContents[0], generatedStuff.Length);
                pcbOutput = (uint)generatedStuff.Length;
            }

            return 0;
        }

        #endregion
    }
}
